package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"strconv"
	"user/models/mysql"
	"user/pkg"

	"user/internal/svc"
	"user/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderLogic {
	return &OrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderLogic) Order(in *user.OrderRequest) (*user.OrderResponse, error) {
	// todo: add your logic here and delete this line

	var good mysql.Good
	err := good.GoodFind(int(in.GoodId))
	if err != nil {
		return nil, fmt.Errorf("商品不存在")
	}

	NumberIng := uuid.NewString()
	Total := good.Price * int(in.Num)

	o := mysql.Order{
		Model:     gorm.Model{},
		UserId:    int(good.ID),
		Total:     Total,
		Numbering: NumberIng,
	}

	err = o.OrderCreate()

	if err != nil {
		return nil, fmt.Errorf("订单生成失败")
	}
	og := mysql.OrderGood{
		Model:   gorm.Model{},
		OrderId: good.GoodId,
		Price:   good.Price,
		Title:   in.Title,
	}
	err = og.OrderGoodCreate()
	if err != nil {
		return nil, fmt.Errorf("订单生成失败")
	}

	Alipay := pkg.Alipay{
		Subject:     in.Title,
		OutTradeNo:  NumberIng,
		TotalAmount: strconv.Itoa(Total),
	}
	url := Alipay.Pay()
	return &user.OrderResponse{
		OrderId: int64(o.ID),
		Url:     url,
	}, nil
}
